<?php

class C_challenge extends CI_Controller 
{
	public function __construct()
	{
		parent::__construct();
		
		//Checking that the user is authorized to access the page.
		user_authorization();
	}
	
	public function index()
	{	
		//Loading libraries
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->library('table');
				
		//get user id from the session
		$cUserID = $this->session->userdata('user_userid');
						
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
				
		// get list of challenges that the current user is the owner
		$owner_challenges = $this->challenge->get_owner_challenge_list($cUserID);
		
		// get list of challenges that the current user is the participant
		$participant_challenges = $this->challenge->get_participant_challenge_list($cUserID);
		
		if (!empty($owner_challenges))
		{
			//populate the challenge table
			$this->_populate_owner_challenge_table($owner_challenges);
			
			//Generating table of challenges that the current user is the owner
			$page_data['owner_challenge_table'] = $this->table->generate();		
			
			//Setting the delimiters for error messages so they can be styled by CSS.
			$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
					
			//Setting the form validation rules.
			$this->form_validation->set_rules('owner_challenge_table', 'checkbox_challenge', 'callback_delete_checkbox_check');
			
			if ($this->form_validation->run())
			{
				foreach ($owner_challenges as $challenge)
				{
					$challenge_id = $challenge['id'];
					$isDeleted = $this->input->post($challenge_id);
					if ($isDeleted === "delete")
					{
						if ($this->challenge->delete($challenge_id) === FALSE)
						{
							//Setting error messages for incorrect user information.
							$page_data['delete_challenge_error'] = 
								'<p class="error">Cannot delete challenge' . $challenge['name']. '!!!</p>';
						}
					}
				}
				redirect('c_challenge', 'refresh');
			}
			
			//Inform the view that there is challenges.
			$page_data['owner_challenges_exists'] = TRUE;
		}
		else //If empty...
		{
			//... inform the view that there is no challenges...
			$page_data['owner_challenges_exists'] = FALSE;
			
			//... and set error message.
			$page_data['owner_challenge_table'] = '<p class="confirmation">You have not created any challenge.</p>';
		}
		
		
		if (!empty($participant_challenges))
		{
			//populate the challenge table
			$this->_populate_participant_challenge_table($participant_challenges);
			
			//Generating table of challenges that the current user is the owner
			$page_data['participant_challenge_table'] = $this->table->generate();		
		}	
		else //If empty...
		{
			//... inform the view that there is no challenges...
			$page_data['participant_challenges_exists'] = FALSE;
			
			//... and set error message.
			$page_data['participant_challenge_table'] = '<p class="confirmation">You are not a participant in any challenge.</p>';
		}
		
		//Setting default "delete-challenge-error-message" if it hasnt been set.
		if (!isset($page_data['delete_owner_challenge_error'])) {
			$page_data['delete_owner_challenge_error'] = '';
		}
		
		// get the number of pending challenge invitations of the current user
		$page_data['num_of_pending_invitation'] = $this->challenge->get_num_pending_invitation($cUserID);
		
		//Loading page views.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge', $page_data);
		$this->load->view('templates/v_footer');
	}
		
	function _populate_owner_challenge_table ($challenges)
	{
		$this->table->set_heading('', 'No.', 'Challenge Name', 'Abstract', 'Status', 'Actions');
		$i = 0;
		foreach ($challenges as $challenge)
		{
			//Adding an "delete-challenge-checkbox" to the challenge array.
			$challenge['checkbox'] = form_checkbox($challenge['id'], 'delete', FALSE);
			$challenge['status'] = $this->challenge->convert_status($challenge['status']);
			
			// ONLY allow the owner to add participant once he changes the challenge's status to ACTIVE	
			if ($challenge['status'] === "Active")
			{
				$this->table->add_row(
					$challenge['checkbox'], ++$i, $challenge['name'], $challenge['abstract'], $challenge['status'],
					anchor('c_challenge/view/'.$challenge['id'],'view',array('class'=>'view')).' '.
					anchor('c_challenge/edit/'.$challenge['id'],'edit',array('class'=>'edit')).' '.
					anchor('c_challenge/delete/'.$challenge['id'],'delete',array('class'=>'delete',
							'onclick'=>"return confirm('Are you sure want to delete this challenge?')")).' '.
					anchor('c_challenge/update_task/'.$challenge['id'],'update task',array('class'=>'task')).' '.
					anchor('c_challenge/participants/'.$challenge['id'],'change participant',array('class'=>'change participant')).' '.
					anchor('c_challenge/participate/'.$challenge['id'],'participate',array('class'=>'participate'))
				);	
			}
			elseif ($challenge['status'] === "Inactive")
			{
				$this->table->add_row(
					$challenge['checkbox'], ++$i, $challenge['name'], $challenge['abstract'], $challenge['status'],
					anchor('c_challenge/view/'.$challenge['id'],'view',array('class'=>'view')).' '.
					anchor('c_challenge/edit/'.$challenge['id'],'edit',array('class'=>'edit')).' '.
					anchor('c_challenge/delete/'.$challenge['id'],'delete',array('class'=>'delete',
							'onclick'=>"return confirm('Are you sure want to delete this challenge?')")).' '.
					anchor('c_challenge/update_task/'.$challenge['id'],'update task',array('class'=>'task'))
					);
			}
			elseif ($challenge['status'] === "Finished")
			{
				$this->table->add_row(
					$challenge['checkbox'], ++$i, $challenge['name'], $challenge['abstract'], $challenge['status'],
					anchor('c_challenge/view/'.$challenge['id'],'view',array('class'=>'view')).' '.
					anchor('c_challenge/delete/'.$challenge['id'],'delete',array('class'=>'delete',
							'onclick'=>"return confirm('Are you sure want to delete this challenge?')"))
					);				
			}
			
		}
		
		//Setting alternative table template.
		$table_template = array(	'row_alt_start'	=> '<tr class="alt_tr">',
									);
		$this->table->set_template($table_template);
		
		//Generating table of challenges.
		//$page_data['owner_challenge_table'] = $this->table->generate();
		
		//return $page_data;
	}	
		
	function _populate_participant_challenge_table ($challenges)
	{
		$this->table->set_heading('', 'No.', 'Challenge Name', 'Abstract', 'Status', 'Actions');
		$i = 0;
		foreach ($challenges as $challenge)
		{
			//Adding an "delete-challenge-checkbox" to the challenge array.
			$challenge['checkbox'] = form_checkbox($challenge['id'], 'delete', FALSE);
			$challenge['status'] = $this->challenge->convert_status($challenge['status']);	
			
			// users are allowed to participate only when the challenge is active; 
			// otherwise (when the challenge is finished/closed) they could view the result only
			if ($challenge['status'] === "Active")
			{
				$this->table->add_row(
					$challenge['checkbox'], ++$i, $challenge['name'], $challenge['abstract'], $challenge['status'],
					anchor('c_challenge/view/'.$challenge['id'],'view',array('class'=>'view')).' '.
					anchor('c_challenge/participate/'.$challenge['id'],'participate',array('class'=>'participate'))
			  	);
			}
			else
			{
				$this->table->add_row(
					$challenge['checkbox'], ++$i, $challenge['name'], $challenge['abstract'], $challenge['status'],
					anchor('c_challenge/view/'.$challenge['id'],'view',array('class'=>'view'))
		  		);
			}
		}
		
		//Setting alternative table template.
		$table_template = array(	'row_alt_start'	=> '<tr class="alt_tr">',
									);
		$this->table->set_template($table_template);
		
		//Generating table of challenges.
		//$page_data['owner_challenge_table'] = $this->table->generate();
		
		//return $page_data;
	}
	
	public function participants($challenge_id) {
		
		//Getting the current user id.
		$user_id = $this->session->userdata('user_userid');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		//Loading the challenge.
		$this->challenge->load_challengedata($challenge_id);
		
		//Fetching the owner id of the challenge.
		$owner_id = $this->challenge->get_info(array('owner_id'));
		
		//Loading header and menu view.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		
		//Checking that the user is the owner of the challenge and therefore is authorized to edit participation.
		if ($user_id == $owner_id) {
			//Loading libraries.
			$this->load->helper('form');
			$this->load->library('table');
			
			//Fetching all users that are participating in the challenge.
			$participants = $this->challenge->get_participants_list();
			
			//Storing if any changes was made.
			$changes_made = FALSE;
			
			//Setting a result message for submitted changes.
			$page_data['submit_result'] = '';
			
			//If changes are submitted then do changes.
			if ($this->input->post('submit_changes')) {
				//Go thru all users to see if their participation has changed.
				foreach ($participants as $p) {
					//If the original participation was false and the new participation is not false then the user should be added.
					if ($p['participation'] == FALSE && $this->input->post('add_user_' . $p['user_id']) != FALSE) {
						//Add the participant. Default values for invitation_status, participation_status and invitation_date.
						$success = $this->challenge->add_participant(array('user_id' => $p['user_id']));
						
						if ($success) {
							//Stores that changes was made.
							$changes_made = TRUE;
						}
					}
					
					//If the original participation was not false and the new participation is false then the user should be removed.
					if ($p['participation'] != FALSE && $this->input->post('add_user_' . $p['user_id']) == FALSE) {
						//Remove the participant.
						$success = $this->challenge->update_participant(array(	'user_id'				=> $p['user_id'],
																				'participation_status'	=> 2 //2 means deleted.
																				));
						
						if ($success) {
							//Stores that changes was made.
							$changes_made = TRUE;
						}
					}
				}
				
				//If there was any changes then the participation list needs to be updated.
				if ($changes_made) {
					//Fetching all users that are participating in the challenge, again.
					$participants = $this->challenge->get_participants_list();
					
					//Changing the result message to a confirmation of changes.
					$page_data['submit_result'] = '<p class="confirmation">Your changes was successfully performed.</p>';
				}
				else {
					//Changing the result message to a error message.
					$page_data['submit_result'] = '<p class="error">No changes was done.</p>';
				}
			}
			
			//Create an array for table data.
			$table_data = array(array('Username', 'E-mail', 'Added'));
			
			//Fetching the owner id for the challenge.
			$owner_id = $this->challenge->get_info(array('owner_id'));
			
			//Put all user information into the table array.
			foreach ($participants as $p) {
				//Creating a user object.
				$this->load->model('m_user', 'user');
				$this->user->load_userdata($p['user_id']);
				
				//Fetching information about the user.
				$user_info = $this->user->get_info(array('username', 'email',));
				
				//Checking if the user is the owner. If so, don't put out any checkbox.
				if ($p['user_id'] != $owner_id) {
					//Adding an "user-added-checkbox" to the user array.
					$user_info['checkbox'] = form_checkbox('add_user_' . $p['user_id'], 'added', $p['participation']);
				}
				else {
					$user_info['checkbox'] = 'Owner';
				}
				
				//Adding the user information to the table.
				$table_data[] = $user_info;
			}
			
			//Generating table of users.
			$page_data['user_table'] = $this->table->generate($table_data);
			
			//Sending the challenge id to the view for use in the form open link.
			$page_data['challenge_id'] = $challenge_id;
			
			//Load view for editing participants.
			$this->load->view('pages/v_challenge_participants', $page_data);
		}
		else {
			//Loading view for not having access to the edit participants view.
			$this->load->view('pages/v_challenge_participants_unauthorized');
		}
		
		//Loading footer view.
		$this->load->view('templates/v_footer');
	}
	
	public function create_challenge()
	{
		//Loading functions for form handling.
		$this->load->helper('form');
		$this->load->library('form_validation');	
		
		//Loading page header and menu.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		
		//Setting the delimiters for error messages so they can be styled by CSS.
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
		
		//Setting the form validation rules.
		$this->form_validation->set_rules('vName', 'Name', 'required');
		$this->form_validation->set_rules('vAbstract', 'Abstract', 'required');
		$this->form_validation->set_rules('vDescription', 'Description', 'required');		
		
		//Resetting login error message.
		$view_data['create_error'] = '';
		
		//Validating data input.											
		if ($this->form_validation->run())
		{
			//Creating a challenge object.
			$this->load->model('m_challenge', 'challenge');
			
			//Getting challenge information
			$cName = $this->input->post('vName'); 
			$cAbstract = $this->input->post('vAbstract');
			$cDescription = $this->input->post('vDescription');
			$cStatus = 0;
			switch ($this->input->post('vStatus'))  
			{
				case 'inactive':
					$cStatus = 0;
					break;
				case 'active':
					$cStatus = 1;
					break;
			}
			
			//TODO: NEED TO VALIDATE INPUT!!!
			if ($this->challenge->challenge_exists($cName))
			{	
				//Setting error messages for duplicating challenge's name.
				$view_data['create_error'] = 
								'<p class="error">A challenge with this name already exists, please use a different name.</p>';
			}			
			else
			{			
				//get userid from the session
				$cUserID = $this->session->userdata('user_userid');
				
				//Get user object
				$this->load->model('m_user', 'user');
				
				//Loading userdata into the user object.
				$this->user->load_userdata($cUserID);		
				
				//Getting username and signup date.
				$cUserInfo = $this->user->get_info(array('username', 'signup_date'));
				
				//Trying to create challenge.
				if ($this->challenge->create(array(	'cName' => $cName, 'cAbstract' => $cAbstract, 'cStatus' => $cStatus,
													'cDescription' => $cDescription, 'cUserID' => $cUserID))) 
				{
					//redirect('c_challenge/create_challenge', 'refresh');
					$view_data['create_error'] = '<p class="confirmation">The challenge is created successfully.</p>';
				}
				else 
				{
					//Setting error messages for incorrect challenge information.
					$view_data['create_error'] = '<p class="error">Challenge information is not valid.</p>';	
				}
			}
		}		
		
		//keep inserted value
		$view_data['name'] = set_value('vName');		
		$view_data['description'] = set_value('vDescription');
		$view_data['abstract'] = set_value('vAbstract');
		$status = array('inactive'	=> FALSE, 
						'active'	=> FALSE, 
					   ); 
					   
		switch (set_value('vStatus'))  
		{
			case 1:
				$status['active'] = TRUE;
				break;
			default:
				$status['inactive'] = TRUE;
				break;
		}
		$view_data['status'] = $status;
				
		//reload the create challenge page.
		$this->load->view('pages/v_challenge_create', $view_data);
		
		//Loading footer.
		$this->load->view('templates/v_footer');
	}
		
	public function view($challenge_id) 
	{	
		//Loading page header and menu.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');	
		$this->load->library('table');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge'); //Create object.
		$this->challenge->load_challengedata($challenge_id); //Load object.
 
		// get challenge details
		$data = $this->challenge->get_info(array('all_info'));
		
		//Converting the status to human readable.
		$data['status'] = $this->challenge->convert_status();
		
		//Converting the description so it shows linebreaks correctly.
		$data['description'] = $this->challenge->convert_description();
		
		// set link back to main page of challenge
		//$data['link_back'] = anchor('c_challenge', 'Back to list of challenges', array('class' => 'back'));
		
		// get list of participants and their participation percentage
		$participation_statistic = $this->challenge->get_participation_statistic($challenge_id);
		
		//populate the challenge table
		$this->_populate_participation_statistic_table($challenge_id, $participation_statistic);
		
		//Generating table of challenges that the current user is the owner
		$data['participation_statistic_table'] = $this->table->generate();
			
		// load view
		$this->load->view('pages/v_challenge_view', $data);
		
		//Loading footer.
		$this->load->view('templates/v_footer');
	}
	
	public function edit($challenge_id) 
	{	
		//Loading functions for form handling.
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge'); //Create
		$this->challenge->load_challengedata($challenge_id); //Load
		$challenge = $this->challenge->get_info(array('all_info')); //Fetch info
		
		$view_data['name'] = $challenge['name'];		
		$view_data['description'] = $challenge['description'];
		$view_data['abstract'] = $challenge['abstract'];							
		
		// radio buttons are set to visible or invisible depends on the current status of the challenge
		$view_data['isActive'] = $view_data['isInactive'] = $view_data['isFinished'] = FALSE;
		//inactive: show all 3 choices for changing the status (remain inactive, become active or finished)
		if ($challenge['status'] == 0) 
		{					   
			$view_data['isInactive'] = TRUE;	
		}		
		//active: show 2 choices for changing the status (remain active or finished)	   
		elseif ($challenge['status'] == 1)
		{
			$view_data['isActive'] = TRUE;
		}
		
		$status = array('inactive'	=> FALSE, 
						'active'	=> FALSE, 
						'finished'	=> FALSE
					   ); 
		
		switch ($challenge['status'])  
		{
			case 1:
				$status['active'] = TRUE;
				break;
			case 2:
				$status['finished'] = TRUE;
				break;
			case 0:
				$status['inactive'] = TRUE;
				break;
		}
		$view_data['status'] = $status;
		
		// set link back to main page of challenge
		$view_data['link_back'] = anchor('c_challenge','Back to list of challenges',array('class'=>'back'));
		$view_data['edit_error'] = '';
		$view_data['action'] = site_url('c_challenge/update_challenge/' . $challenge_id);
		
		//Loading pages
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_edit', $view_data);
		$this->load->view('templates/v_footer');							
	}
	
	function update_challenge($challenge_id)
	{
		//Loading functions for form handling.
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		//Setting the delimiters for error messages so they can be styled by CSS.
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
		
		//Setting the form validation rules.
		$this->form_validation->set_rules('vName', 'Name', 'required');
		$this->form_validation->set_rules('vAbstract', 'Abstract', 'required');
		$this->form_validation->set_rules('vDescription', 'Description', 'required');
		$this->form_validation->set_rules('vStatus', 'Status', 'required');	
		
		//Resetting login error message.
		$view_data['edit_error'] = '';
		
		//Validating data input.											
		if ($this->form_validation->run())
		{			
			//get user id from the session
			$cOwnerID = $this->session->userdata('user_userid');
		
			//Getting challenge information
			$cName = $this->input->post('vName'); 
			$cAbstract = $this->input->post('vAbstract');
			$cDescription = $this->input->post('vDescription');
			$cStatus = 0;
			switch ($this->input->post('vStatus'))  
			{
				case 'active':
					$cStatus = 1;
					break;
				case 'finished':
					$cStatus = 2;
					break;
				case 'inactive':
					$cStatus = 0;
					break;
			}
			
			//Creating a challenge object.
			$this->load->model('m_challenge', 'challenge');
		
			if ($this->challenge->challenge_name_available($cName, $challenge_id))
			{	
				//Trying to update challenge.
				if ($this->challenge->update(array( 'cID' => $challenge_id, 'cName' => $cName, 'cAbstract' => $cAbstract, 
													'cDescription' => $cDescription, 'cStatus' => $cStatus))) 
				{
					//redirect('c_challenge', 'refresh');
					$view_data['edit_error'] = '<p class="confirmation">The challenge is updated successfully.</p>';
				}
				else 
				{
					//Setting error messages for incorrect challenge information.
					$view_data['edit_error'] = '<p class="error">Challenge information is not valid.</p>';	
				}
			}			
			else
			{							
				//Setting error messages for duplicating challenge's name.
				$view_data['edit_error'] = 
								'<p class="error">A challenge with this name already exists, please use a different name.</p>';	
			} 
		}
		
		//keep inserted value
		$view_data['name'] = set_value('vName');		
		$view_data['description'] = set_value('vDescription');
		$view_data['abstract'] = set_value('vAbstract');
		
		$view_data['isActive'] = $view_data['isInactive'] = $view_data['isFinished'] = FALSE;
			
		$status = array('inactive'	=> FALSE, 
						'active'	=> FALSE, 
						'finished'	=> FALSE
					   ); 
		
		switch (set_value('vStatus'))  
		{
			case 'active':
				$status['active'] = TRUE;
				$view_data['isActive'] = TRUE;
				break;
			case 'finished':
				$status['finished'] = TRUE;
				$view_data['isFinished'] = TRUE;
				break;
			default:
				$status['inactive'] = TRUE;
				$view_data['isInactive'] = TRUE;
		}
		$view_data['status'] = $status;
		
		// set link back to main page of challenge
		//$view_data['link_back'] = anchor('c_challenge','Back to list of challenges',array('class'=>'back'));
		$view_data['action'] = site_url('c_challenge/update_challenge/' . $challenge_id);
		
		//Loading pages
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_edit', $view_data);
		$this->load->view('templates/v_footer');
	}
	
	public function delete($challenge_id)
	{		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		if ($this->challenge->delete($challenge_id) === FALSE)
		{
			//Setting error messages for incorrect user information.
			$page_data['delete_challenge_error'] = '<p class="error">Cannot delete challenge' . $challenge['name']. '!!!</p>';
		}
		else
		{
			redirect('c_challenge', 'refresh');
		}
	}
	
	public function delete_checkbox_check()
	{
		//TODO: how to pass $challenges as a parameter???, confirm pop-up
		
		//get user id from the session
		$cUserID = $this->session->userdata('user_userid');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		//Get information about all challenges created by the user.
		$challenges = $this->challenge->get_challenge_list($cUserID);
		
		foreach ($challenges as $challenge)
		{
			$challenge_id = $challenge['id'];
			$isDeleted = $this->input->post($challenge_id);
			if ($isDeleted === "delete")
			{
				return TRUE;
			}
		}
			
		$this->form_validation->set_message('delete_checkbox_check', 'Please choose at least one challenge for deleting.');
		return FALSE;
	}

	public function confirm_invitation()
	{
		//Loading functions for form and table handling.
		$this->load->helper('form');
		$this->load->library('form_validation');	
		$this->load->library('table');
							
		//get user id from the session
		$userID = $this->session->userdata('user_userid');
						
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
				
		//Resetting login error message.
		$view_data['confirm_error'] = '';
		
		// get all challenges that needs the user to confirm whether he wants to join in or not
		$pending_challenges = $this->challenge->get_challenges_with_pending_invitation($userID);
		if (!empty($pending_challenges))
		{			
			// populate the pending challenges table
			$this->_populate_pending_challenge_table($pending_challenges);
				
			//Generating table of challenges that the current user is the owner
			$view_data['pending_challenge_table'] = $this->table->generate();	
			
			
			//if the invitation status is changed then the view will pop up a msg for confirmation DOESN'T WORK YET!
			//$view_data['invitation_confirmation_updated'] = $this->_invitation_confirmation_updated($pending_challenges);	
			
			//If changes are submitted then do changes.
			if ($this->input->post('submit_confirmation')) 
			{
				foreach ($pending_challenges as $challenge)
				{
					$challengeID = $challenge['id'];
					$confirm_result = $this->input->post($challengeID);
					if ($this->challenge->update_participation_status($challengeID, $userID, $confirm_result) === FALSE)
					{
						//Setting error messages for incorrect user information.
						$page_data['confirm_error'] = 
							'<p class="error">Cannot update the participation status for ' . $challenge['name']. ' challenge!</p>';
					}
				}
				redirect('c_challenge/confirm_invitation', 'refresh');
			}
			
			//... inform the view that there is pending challenge invitation...
			$view_data['pending_invitation_exists'] = TRUE;			
		}	
		else //If empty...
		{
			//... inform the view that there is no pending challenge invitation...
			$view_data['pending_invitation_exists'] = FALSE;
			
			//... and set error message.
			$view_data['pending_challenge_table'] = '<p class="confirmation">You have no challenge invitation left.</p>';
		}
					
		//Loading pages.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_confirm_invitation', $view_data);
		$this->load->view('templates/v_footer');
	}
	
	function _populate_pending_challenge_table ($challenges)
	{
		$this->table->set_heading('No.', 'Challenge Name', 'Abstract', 'View', 'Invitation Confirmation');
		$i = 0;
		foreach ($challenges as $challenge)
		{					
			//Adding 2 radio buttons for accepting and denying the invitation to each row.
			$challenge['accept'] = form_radio($challenge['id'], 'accept', FALSE);			
			$challenge['deny'] = form_radio($challenge['id'], 'deny', FALSE);		
			$challenge['not_now'] = form_radio($challenge['id'], 'not_now', TRUE);
			
			$this->table->add_row(
				++$i, $challenge['name'], $challenge['abstract'],
				anchor('c_challenge/view/'.$challenge['id'],'view',array('class'=>'view')), 
				$challenge['accept']. 'Accept' .' '. $challenge['deny'] . 'Deny' .' '. $challenge['not_now'] . 'Not Now'
		  	);
		}
		
		//Setting alternative table template.
		$table_template = array('row_alt_start'	=> '<tr class="alt_tr">',);
		$this->table->set_template($table_template);
	}
	
	function _invitation_confirmation_updated($pending_challenges)
	{		
		foreach ($pending_challenges as $challenge)
		{
			$challenge_id = $challenge['id'];
			$invitation_status = $this->input->post($challenge_id);
			if ($invitation_status === "accept" || $invitation_status === "deny")
			{
				return TRUE;
			}
		}
		return FALSE;
	}
	
	function _populate_participation_statistic_table($challenge_id, $participation_statistic)
	{
		$this->table->set_heading('No.', 'Participation Name', 'Task Completion', 'View');
		$i = 0;
		foreach ($participation_statistic as $participation)
		{								
			$this->table->add_row(
				++$i, $participation['name'], $participation['percentage'].'%',
				anchor('c_challenge/participation_view/' . $challenge_id . '/' . $participation['id'],'view',array('class'=>'view'))
		  	);
		}
		
		//Setting alternative table template.
		$table_template = array('row_alt_start'	=> '<tr class="alt_tr">',);
		$this->table->set_template($table_template);		
	}
	
	function participation_view($challenge_id, $participant_id)
	{
		//Loading page header and menu.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');	
		$this->load->library('table');
		 
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		// get list of participants and their participation percentage
		$tasks = $this->challenge->get_all_task_info($challenge_id, $participant_id);
		
		// if there is no task available then dont populate the task table
		if (count($tasks) == 0)
		{
			$data['noTask'] = TRUE;
			$data['task_table'] = FALSE;
		}
		else
		{	
			$data['noTask'] = FALSE;		
			
			// populate the task table
			$this->_populate_task_contribution_table($tasks);
			
			// Generating table of challenges that the current user is the owner
			$data['task_table'] = $this->table->generate();	
		}
		
			
		// load view
		$this->load->view('pages/v_challenge_participation_view', $data);
		
		// Loading footer.
		$this->load->view('templates/v_footer');
	}
	
	function _populate_task_contribution_table($tasks)
	{
		$this->table->set_heading('No.', 'Task Name', 'Task Status', 'Link', 'Comment');
		$i = 0;
		foreach ($tasks as $task)
		{					
			if ($task['link'] == '') // the participant hasnt uploaded image result to the task
			{
				$this->table->add_row(	++$i, $task['name'], $task['status'], 
										'', '');
			}						
			else // the participant finished the task and uploaded image
			{
				$this->table->add_row(	++$i, $task['name'], $task['status'], 
										anchor($task['link'], $task['title']),
										$task['comment']);
			}
		}
		
		//Setting alternative table template.
		$table_template = array('row_alt_start'	=> '<tr class="alt_tr">',);
		$this->table->set_template($table_template);		
	}
	
	public function update_task($challenge_id)
	{
		//Loading functions for form handling.
		$this->load->helper('form');
		$this->load->library('form_validation');	
		$this->load->library('table');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge'); //Create
		$this->challenge->load_challengedata($challenge_id); //Load
		$challenge = $this->challenge->get_info(array('all_info')); //Fetch info
		$challenge['status'] = $this->challenge->convert_status($challenge['status']);
		
		$view_data['challenge_name'] = $challenge['name'];		
		$view_data['challenge_abstract'] = $challenge['abstract'];	
		$view_data['challenge_status'] = $challenge['status'];						
		
		// set link back to main page of challenge
		$view_data['link_back'] = anchor('c_challenge','Back to list of challenges',array('class'=>'back'));
		
		//Setting the delimiters for error messages so they can be styled by CSS.
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
				
		//Resetting login error message.
		$view_data['task_result'] = '';
		
		//Validating data input.		
		if ($this->input->post('add_task'))
		{
			//Setting the form validation rules.
			$this->form_validation->set_rules('vName', 'Task Name', 'required');
			$this->form_validation->set_rules('vDescription', 'Task Description', 'required');	
			
			if ($this->form_validation->run())
			{			
				//Getting challenge information
				$tName = $this->input->post('vName'); 
				$tDescription = $this->input->post('vDescription');
				
				if ($this->challenge->task_exists($tName, $challenge_id))
				{	
					//Setting error messages for duplicating challenge's name.
					$view_data['task_result'] = 
						'<p class="error">The challenge has a task with that name already, please use a different name.</p>';
				}			
				else
				{					
					//Trying to create challenge.
					if ($this->challenge->add_task(array(	'name' => $tName, 'description' => $tDescription, 
															'challenge_id' => $challenge_id))) 
					{
						$view_data['task_result'] = '<p class="confirmation">The task is added successfully.</p>';
					}
					else 
					{
						//Setting error messages for incorrect challenge information.
						$view_data['task_result'] = '<p class="error">Task information is not valid.</p>';	
					}
				}
			}	
		}	
		
		// get a list of all tasks that belongs to the challenge.
		$tasks = $this->challenge->get_all_task($challenge_id);	
		
		if (!empty($tasks))
		{
			//populate the task table
			$this->_populate_task_table($challenge_id, $tasks);
			
			//Generating table of challenges that the current user is the owner
			$view_data['task_table'] = $this->table->generate();		
			
			if ($this->input->post('delete_task'))
			{					
				//Setting the form validation rules.
				$this->form_validation->set_rules(	'task_table', 'checkbox_task', 
													'callback_delete_task_checkbox_check['.$challenge_id.']');
				
				if ($this->form_validation->run())
				{
					foreach ($tasks as $task)
					{
						$task_id = $task['id'];
						$isDeleted = $this->input->post($task_id);
						if ($isDeleted === "delete")
						{
							if ($this->challenge->delete_task($task_id) === FALSE)
							{
								//Setting error messages for incorrect task information.
								$view_data['task_result'] = 
									'<p class="error">Cannot delete task' . $task['name']. '!!!</p>';
							}
						}
					}	
					redirect("c_challenge/update_task/$challenge_id", 'refresh');	
				}		
			}
			
			//Inform the view that there is task.
			$view_data['task_exists'] = TRUE;
		}
		else //If empty...
		{
			//... inform the view that there is no task...
			$view_data['task_exists'] = FALSE;
			
			//... and set error message.
			$view_data['task_table'] = '<p class="error">You have not created any task.</p>';
		}
		
		//Setting default message if it hasnt been set.
		if (!isset($view_data['task_result'])) {
			$view_data['task_result'] = '';
		}
		
		//keep inserted value
		$view_data['task_name'] = set_value('vName');		
		$view_data['task_description'] = set_value('vDescription');
								
		$view_data['challenge_id'] = $challenge_id;
		//Loading pages
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_task', $view_data);
		$this->load->view('templates/v_footer');
	}
	
	function participate($challenge_id)
	{
		//Load table helper.
		$this->load->library('table');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge'); //Create
		$this->challenge->load_challengedata($challenge_id); //Load
		
		//Fetch challenge name.
		$view_data['challenge_name'] = $this->challenge->get_info(array('name'));
		
		//Fetching the user id for later use.
		$user_id = $this->session->userdata('user_userid');
		
		// get a list of all tasks that belongs to the challenge.
		$tasks = $this->challenge->get_all_task($challenge_id);
		
		//Checking if ther are tasks in the chosen challenge.
		if (!empty($tasks))
		{
			//Setting table headings.
			$this->table->set_heading('Task Name', 'Link', 'Comment', 'Actions');
			
			//Going thru all tasks to print them and any contributions connected to them.
			foreach ($tasks as $t) {
				//Fetching information about the contribution.
				$contribution = $this->challenge->fetch_contribution(array(	'task_id'	=> $t['id'],
																			'user_id'	=> $user_id));
				
				//Selecting what to print based on if there are a contribution to the task.
				if ($contribution === FALSE) {
					$contribution_link		= '';
					$contribution_comment	= '';
				}
				else {
					$contribution_link		= anchor($contribution['link'], $contribution['title']);
					$contribution_comment	= $contribution['comment'];
				}
				
				//Adding the contributed link and comment to the table as well as possible actions.
				$this->table->add_row($t['name'], $contribution_link, $contribution_comment, anchor('c_challenge/view_task/' . $t['id'], 'View task') . ' ' . anchor('c_challenge/upload_contribution/' . $t['id'], 'Upload contribution'));
			}
			
			//Generating table of the contributions of the user.
			$view_data['task_table'] = $this->table->generate();
		}
		else //If there are no tasks in the challenge, then...
		{
			//... set an error message.
			$view_data['task_table'] = '<p class="error">There are no tasks in this challenge yet!</p>';
		}
		
		//Loading pages.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_participate', $view_data);
		$this->load->view('templates/v_footer');
	}
	
	function upload_contribution($task_id = FALSE)
	{
		//---------------------------------------------------------
		//Pre-calculations.
		
		//Fetching/Setting the task id to the session.
		if ($task_id === FALSE) {
			$task_id = $this->session->userdata('contribution_task_id');
		}
		else {
			$this->session->set_userdata('contribution_task_id', $task_id);
		}
		
		//Load helpers.
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge'); //Create
		
		//Get the challenge ID for the challenge the task belongs to.
		$challenge_id = $this->challenge->get_challenge_id_from_task_id($task_id);
		
		//Load the challenge object.
		$this->challenge->load_challengedata($challenge_id); //Load
		
		//Sending the challenge ID to the view.
		$view_data['challenge_id'] = $challenge_id;
		
		//Fetch challenge name.
		$view_data['challenge_name'] = $this->challenge->get_info(array('name'));
		
		//Get the user id.
		$user_id = $this->session->userdata('user_userid');
		
		//Get information about the task.
		$tasks = $this->challenge->get_all_task_info($challenge_id, $user_id);
		
		//Going thru all contributions from the user in this challenge to get information about the actual task.
		foreach ($tasks as $t) {
			if ($t['id'] == $task_id) {
				$task = $t;
			}
		}
		
		//Sending the task name to the view.
		$view_data['task_name'] = $task['name'];
		
		//Deciding what the change message should show.
		if (isset($_POST['contribution_submit'])) {
			$view_data['change_message'] = '<p class="error">No changes was made!</p>';
		}
		else {
			$view_data['change_message'] = '';
		}
		
		//---------------------------------------------------------
		//Validation.
		
		//Putting valus from the database into the form as default.
		$repopulation = array(	'link'		=> $task['link'],
								'title'		=> $task['title'],
								'comment'	=> $task['comment']
								);
		
		//Setting the delimiters for error messages so they can be styled by CSS.
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
		
		//Setting validation rules.
		$this->form_validation->set_rules('link', 'link', 'required|max_length[256]');
		$this->form_validation->set_rules('title', 'title', 'required|max_length[128]');
		
		//Determine if the entered data was OK.
		if ($this->form_validation->run() == FALSE) {
			//If the task isn't done and the submission was unsuccessful, then repopulate the form with values the user entered.
			if ($task['status'] == 'not done') {
				$repopulation = array(	'link'		=> set_value('link'),
										'title'		=> set_value('title'),
										'comment'	=> set_value('comment')
										);
			}
		}
		else {
			//Loading parameters needed to update the contribution
			$parameters['link']		= $this->input->post('link');
			$parameters['title']	= $this->input->post('title');
			$parameters['comment']	= $this->input->post('comment');
			$parameters['task_id']	= $task_id;
			$parameters['user_id']	= $user_id;
			
			//Update the contribution.
			$success = $this->challenge->update_contribution($parameters);
			
			if ($success) {
				//Starts updating the information in the form.
					//Get information about the task.
					$tasks = $this->challenge->get_all_task_info($challenge_id, $user_id);
					
					//Going thru all contributions from the user in this challenge to get information about the actual task.
					foreach ($tasks as $t) {
						if ($t['id'] == $task_id) {
							$task = $t;
						}
					}
					
					//Putting valus from the database into the form.
					$repopulation = array(	'link'		=> $task['link'],
											'title'		=> $task['title'],
											'comment'	=> $task['comment']
											);
				//Stops updating the information in the form.
				
				$view_data['change_message'] = '<p class="confirmation">Your changes was submitted!</p>';
			}
		}
		
		//Send the repopulation values to the view.
		$view_data['repopulation'] = $repopulation;
		
		//---------------------------------------------------------
		//Post-calculations.
		
		//Loading pages.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_upload_contribution', $view_data);
		$this->load->view('templates/v_footer');
	}
	
	function view_task($task_id)
	{
		$view_data['task_id'] = $task_id;
		
		//Loading pages.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_logedin');
		$this->load->view('pages/v_challenge_task_view', $view_data);
		$this->load->view('templates/v_footer');
	}
	
	function _populate_task_table ($challenge_id, $tasks)
	{
		$this->table->set_heading('', 'No.', 'Task Name', 'Task Description', 'Delete');
		$i = 0;
		foreach ($tasks as $task)
		{
			//Adding an "delete-task-checkbox" to the task array.
			$task['checkbox'] = form_checkbox($task['id'], 'delete', FALSE);
			
			$this->table->add_row(
				$task['checkbox'], ++$i, $task['name'], $task['description'], 
				anchor('c_challenge/delete_task/' . $challenge_id . '/' . $task['id'],'delete',array('class'=>'delete',
						'onclick'=>"return confirm('Are you sure want to delete this task?')"))
			);			
		}
		
		//Setting alternative table template.
		$table_template = array(	'row_alt_start'	=> '<tr class="alt_tr">',
									);
		$this->table->set_template($table_template);
	}	
	
	public function delete_task($challenge_id, $task_id)
	{
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		if ($this->challenge->delete_task($task_id) === FALSE)
		{
			//Setting error messages for unsuccessful task deleting.
			$view_data['task_result'] = '<p class="error">Cannot delete task!</p>';
		}
		else
		{
			redirect("c_challenge/update_task/$challenge_id", 'refresh');
		}
	}
	
	public function delete_task_checkbox_check($str, $challenge_id)
	{		
		//Creating a challenge object.
		$this->load->model('m_challenge', 'challenge');
		
		//Get information about all challenges created by the user.
		$tasks = $this->challenge->get_all_task($challenge_id);	
		
		foreach ($tasks as $task)
		{
			$task_id = $task['id'];
			$isDeleted = $this->input->post($task_id);
			if ($isDeleted === "delete")
			{
				return TRUE;
			}
		}
			
		$this->form_validation->set_message('delete_task_checkbox_check', 'Please choose at least one task for deleting.');
		return FALSE;
	}
}
?>